package cn.xspace.wnx.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xspace.android.xafcommon.base.BaseActivity;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.been.PageSizeBean;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.ErrorCode;
import com.xspace.android.xafcommon.util.EventBusConstant;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.T;
import com.xspace.android.xafcommon.view.dialog.ButtonClickListener;
import com.xspace.android.xafcommon.view.dialog.DialogHelp;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import cn.xspace.app.view.TitleBar;
import cn.xspace.library.bean.OrgDeptUserBean;
import cn.xspace.library.bean.Type;
import cn.xspace.library.util.BldNavigation;
import cn.xspace.library.util.MsgType;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.library.util.OkHttpManager;
import cn.xspace.wnx.R;
import cn.xspace.wnx.adapter.HorizontalScrollViewAdapter;
import cn.xspace.wnx.fragment.AddressBookSelectFragment;
import cn.xspace.wnx.fragment.OrganizationSelectFragmentR;
import cn.xspace.wnx.util.Navigator;
import cn.xspace.wnx.util.Notifier;
import cn.xspace.wnx.view.MyHorizontalScrollView;
import de.greenrobot.event.EventBus;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 选择用户界面,发起群聊需要进入该界面
 * <p>
 * 1.包括首次发起群聊 -- 目前该功能已屏蔽
 * 2.添加人员 -- 关键字段KEY_MEMBER_OPERATE 对用成员变量fromType
 * |--包括群组增加人员
 * |--单人发起多人会话增加人员
 * 3.删除人员 -- 同上
 * Created by liuchen on 2016/10/28.
 */
public class SelectMemberActivity extends BaseActivity {

    private static final String TAG = SelectMemberActivity.class.getSimpleName();

    public static final String SELECTED_MEMBERS = "SelectedMembery";
    private TitleBar mTitleBar; //标题栏
    private MyHorizontalScrollView mHorizonScroll; //水平滚动栏
    private RadioGroup rgMemberSelect;
    private RadioButton rbByMember;
    private RadioButton rbByOrg;
    private Fragment addressbookFragment; //通讯录列表
    private Fragment orgazitionFragment; //机构人员列表
    private Fragment currentFragment;

    private String user_id = "";
    private String dept_id = "";
    private String[] tags = new String[]{"通讯录", "组织机构"};
    private int memberSelect = 0;
    private Bundle savedInstanceState;
    HorizontalScrollViewAdapter horizonAdapter;
    //当前群组的成员的所有id的集合
    private ArrayList<String> currentUserIdList = new ArrayList<>();
    //当前群组人员
    private ArrayList<OrgDeptUserBean> currentUserList = new ArrayList<>();
    //选择的人员
    private ArrayList<OrgDeptUserBean> selectUserList = new ArrayList<>();
    //传递过来的数据固定存在此集合,不在改变,用于后续的一些一些判断

    //用于区分是增加人员还是删除人员
    private String fromType = "";
    //要修改的是哪个群组,群组id
    private String group_id = "";
    //群组的群主id
    private String groupOwnerId = "";
    //群组类型,默认为临时会话,该变量在做增删操作时会由上层界面传递数据赋值
    private int group_type = Type.GroupType.TEMP_GROUP;
    //群组成员数量,在删除成员时展示在标题栏的标题上
    private int groupMember;

    private boolean isShowAdressbook = true;

//    private TextView mTopTxt;
//    private ImageView headerLogo;
//    private TextView headerName;
//    private LinearLayout memberSelectHeader;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        this.savedInstanceState = savedInstanceState;
        super.onCreate(savedInstanceState);
        //走完super才会走以下代码,即页面完成初始化后
//        Boolean isShowInfo = PreferencesUtils.getBooleanData("isShowInfo");
//        if (!isShowInfo) { //如果显示过一次就不显示了
//            new Handler().post(new Runnable() {
//                @Override
//                public void run() {
//                    DialogHelp.getDialog(mContext).setMessage(R.string.add_member_info)
//                            .setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//                                    PreferencesUtils.SaveBooleanData("isShowInfo", true);
//                                }
//                            }).show();
//                }
//            });
//        }
    }

    @Override
    protected void getIntentData() {
        super.getIntentData();
        Bundle dataBundle = getIntent().getBundleExtra(BldNavigation.KEY_BUNDLER);
        if (dataBundle != null) { //传递了数据进来,需要将传递过来的数据解析,确定是否可以增加或者删除
            Object list = dataBundle.getSerializable(SelectMemberActivity.SELECTED_MEMBERS);
            String id = dataBundle.getString(ChatInfoActivity.GROUP_ID);
            if (!TextUtils.isEmpty(id)) {
                group_id = id;
            }
            LogUtil.d("groupId>" + id); //本身是群组,存在group_id,没有list;由单人变为群组,没有group_id,但是有用户list集合
            if (list != null) {
//                selectUserList.addAll((ArrayList<OrgDeptUserBean>) list);
                currentUserList.addAll((ArrayList<OrgDeptUserBean>) list);
                for (OrgDeptUserBean bean : currentUserList) {
                    currentUserIdList.add(bean.user_id);
                }
                LogUtil.d("selectUserList.size()>>>" + selectUserList.size());
            }
            fromType = dataBundle.getString(ChatInfoActivity.KEY_MEMBER_OPERATE);
            groupOwnerId = dataBundle.getString(ChatInfoActivity.GROUP_OWNER);
            groupMember = dataBundle.getInt(ChatInfoActivity.GROUP_MEMBER_NUMBER);
            group_type = dataBundle.getInt(ChatInfoActivity.GROUP_TYPE);
            LogUtil.d("fromType>>" + fromType + ">>groupOwnerId>>" + groupOwnerId);
        }
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_member_select);
        horizonAdapter = new HorizontalScrollViewAdapter(mContext, selectUserList, null);
    }

    @Override
    protected void initFindViewById() {
        super.initFindViewById();
        mTitleBar = (TitleBar) findViewById(R.id.title_bar);
        mHorizonScroll = (MyHorizontalScrollView) findViewById(R.id.hsv_member_select);

        rgMemberSelect = (RadioGroup) findViewById(R.id.rg_member_select_header);
        rbByMember = (RadioButton) findViewById(R.id.rb_select_by_member);
        rbByOrg = (RadioButton) findViewById(R.id.rb_select_by_org);

//        mTopTxt = (TextView) findViewById(R.id.txt_top);
//        headerLogo = (ImageView) findViewById(R.id.img_logo_header);
//        headerName = (TextView) findViewById(R.id.txt_name_header);
//        memberSelectHeader = (LinearLayout) findViewById(R.id.linear_member_select_header);
    }

    @Override
    protected void initData() {
        user_id = MyInfoUtil.getMyUserid(mContext);
        dept_id = MyInfoUtil.getUseOrgId(mContext);
        if (!TextUtils.isEmpty(group_id)) { //如果传入的是group_id,则需要访问网络获取数据
            Map<String, Object> getMembersMap = new HashMap<>();
            getMembersMap.put("group_id", group_id);
            getMembersMap.put("user_id", user_id);
            PageSizeBean bean = new PageSizeBean();
            bean.page = 1;
            bean.page_size = 1000;
            getMembersMap.put("pg", bean);
            OkHttpManager.getInstance().commonRequest(Constants.QUERY_GROUP_MEMBERS, getMembersMap)
                    .subscribeOn(Schedulers.io())
                    .map(new Func1<BaseReturnBean, ArrayList<OrgDeptUserBean>>() {
                        @Override
                        public ArrayList<OrgDeptUserBean> call(BaseReturnBean baseReturnBean) {
                            ArrayList<OrgDeptUserBean> dataList = new Gson().fromJson(baseReturnBean.data, new
                                    TypeToken<ArrayList<OrgDeptUserBean>>() {
                                    }.getType());
                            for (OrgDeptUserBean bean : dataList) {
                                currentUserIdList.add(bean.user_id);
                            }
                            return dataList;
                        }
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<ArrayList<OrgDeptUserBean>>() {
                        @Override
                        public void call(ArrayList<OrgDeptUserBean> orgDeptUserBeen) {
                            LogUtil.d(orgDeptUserBeen.size() + "");
                            currentUserList.addAll(orgDeptUserBeen); //群组本身的成员
                            if (isMemberMin()) { //删除人员
                                mTitleBar.setRightLayoutTextView(String.format(getResources().getString(R.string
                                        .number_member_delete_select), memberSelect + ""));
                            } else { //群组增加人员
                                refreshMember(); //访问网络获取到数据后刷新
                                refreshHorizonAdapter(); //刷新水平栏信息
                            }
                            initFragment();
                        }
                    }, new Action1<Throwable>() {

                        @Override
                        public void call(Throwable throwable) {
                            hideWaitDialog();
                            T.showShort(mContext, throwable.getMessage());
                        }
                    });
        } else { //否则是由单人发起的多人会话,传递过来了list集合,直接展示数据即可
            initFragment();
        }
    }

    private void initFragment() {

        if (savedInstanceState != null) { //该逻辑何时进入?
            LogUtil.d(TAG, "wubaojie>>>initFragment: savedInstanceState不为空");
            addressbookFragment = getSupportFragmentManager().findFragmentByTag(tags[0]);
            orgazitionFragment = getSupportFragmentManager().findFragmentByTag(tags[1]);

            if (addressbookFragment == null) {
                addressbookFragment = AddressBookSelectFragment.newInstance(currentUserList, fromType, groupOwnerId);
            }
            if (orgazitionFragment == null) {
                orgazitionFragment = OrganizationSelectFragmentR.newInstance(currentUserList, fromType);
            }
        } else {
            if (isMemberMin()) { //删除人员,可以不加载机构页面,因为不切换
                ArrayList<OrgDeptUserBean> tempList = new ArrayList<>();
                tempList.addAll(currentUserList);
                addressbookFragment = AddressBookSelectFragment.newInstance(tempList, fromType, groupOwnerId);
                orgazitionFragment = OrganizationSelectFragmentR.newInstance(tempList, fromType);
            } else { //否则为增加人员
                addressbookFragment = AddressBookSelectFragment.newInstance(currentUserList, fromType, groupOwnerId);
                orgazitionFragment = OrganizationSelectFragmentR.newInstance(currentUserList, fromType);
            }
        }

        EventBus.getDefault().register(addressbookFragment);
        EventBus.getDefault().register(orgazitionFragment);
        getSupportFragmentManager().beginTransaction().add(R.id.container, addressbookFragment).commit();
        currentFragment = addressbookFragment;
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        mHorizonScroll.initDatas(horizonAdapter);
        refreshMember(); //不访问网络获取数据后刷新
        if (isMemberMin()) { //删除人员时只显示一个通讯录页面即可,不显示机构页面
            rgMemberSelect.setVisibility(View.GONE);
        } else { //添加人员可从机构中选择
//            rgMemberSelect.setVisibility(View.VISIBLE);
            rgMemberSelect.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) {
                    if (checkedId == R.id.rb_select_by_member) { //按人员
                        switchContent(currentFragment, addressbookFragment, 0);
                        currentFragment = addressbookFragment;
                    } else if (checkedId == R.id.rb_select_by_org) { //按机构
                        switchContent(currentFragment, orgazitionFragment, 1);
                        currentFragment = orgazitionFragment;
                    }
                }
            });
        }
        mTitleBar.showRightText();

        if (isMemberMin()) {
            mTitleBar.setTitle(String.format(getResources().getString(R.string.member_delete), groupMember + ""));
            mTitleBar.setRightLayoutTextView(String.format(getResources().getString(R.string
                    .number_member_delete_select), 0 + ""));
        } else {
            mTitleBar.setRightLayoutTextView(String.format(getResources().getString(R.string.number_member_select),
                    memberSelect + ""));
        }

        mTitleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mTitleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isSingleChatToGroup()) { //单聊添加成员变临时会话
                    if (memberSelect > 0) {
//                        if (memberSelect + currentUserList.size() > 50) {
//                            T.showShort(mContext, R.string.group_member_max_hit);
//                        } else {
                        createGroupChat();
//                        }
                    } else {
                        T.showShort(mContext, R.string.min_select_one_member);
                    }

                } else if (isAddMember()) { //群组添加成员
                    if (memberSelect <= 0) {
                        T.showShort(mContext, R.string.min_select_one_member_add);
                    } else {
//                        if (memberSelect + currentUserList.size() > 50) {
//                            T.showShort(mContext, R.string.group_member_max_hit);
//                        } else {
                        AddGroupMembers();
//                        }
                    }

                } else if (isMemberMin()) { //群组删除成员
                    if (memberSelect == 0) {
                        T.showShort(mContext, R.string.min_select_one_member_delete);
                    } else {
                        showConfirmDialog();
                    }
                } else { //TODO 发起群聊,目前发起群聊按钮已隐藏,该逻辑暂时无用,待发起群聊按钮放开再做打算
                    if (memberSelect > 0) {
                        if (memberSelect == 1) { //选择一个人，跳往单聊页面
                            OrgDeptUserBean bean = selectUserList.get(0);
                            Bundle dataBundle = new Bundle();
                            dataBundle.putString(BldNavigation.SENDER_ID, bean.user_id);
                            dataBundle.putInt(BldNavigation.CHAT_TYPE, MsgType.CHAT_SINGLE.toNumber());
                            dataBundle.putString(BldNavigation.CHAT_NAME, bean.user_name);
                            dataBundle.putString(BldNavigation.CHAT_SENDER_LOGO, "");
                            dataBundle.putString(BldNavigation.CHAT_SENDER_SEX, bean.user_sex);
                            Navigator.startChatActivity(mContext, dataBundle);
                            finish();
                        } else {
//                            if (memberSelect > 50) {
//                                T.showShort(mContext, R.string.group_member_max_hit);
//                            } else {
                            createGroupChat();
//                            }
                        }
                    } else {
                        T.showShort(mContext, R.string.min_select_one_member);
                    }
                }

            }
        });


        // 添加滚动回调
        mHorizonScroll.setCurrentImageChangeListener(new MyHorizontalScrollView.CurrentImageChangeListener() {
            @Override
            public void onCurrentImgChanged(int position, View viewIndicator) {
                LogUtil.d(TAG, "wubaojie>>>onCurrentImgChanged: pos:" + position);
            }
        });
        // 添加点击回调
        mHorizonScroll.setOnItemClickListener(new MyHorizontalScrollView.OnItemClickListener() {

            @Override
            public void onClick(View view, int position) {
                LogUtil.d(TAG, "wubaojie>>>onClick: MyHScrollView:pos:" + position);

                OrgDeptUserBean bean = selectUserList.get(position);
                if (isMemberMin()) {
                    if (!TextUtils.isEmpty(groupOwnerId) && groupOwnerId.equals(bean.user_id))
                        return;
                }
                if (isAddMember()) {
                    if (currentUserIdList.contains(bean.user_id))
                        return;
                }
                selectUserList.remove(bean);
                mHorizonScroll.initDatas(horizonAdapter);
                refreshMember(); //选择栏点击后刷新
                //通知更新FragmentUi

                Map<String, Object> addressMap = new HashMap<String, Object>();
                addressMap.put(EventBusConstant.TYPE, EventBusConstant.ACTIVITY_TO_ADDRESSBOOK);
                addressMap.put(EventBusConstant.OPERATE_ID, bean.user_id);
                EventBus.getDefault().post(addressMap);

                Map<String, Object> orgMap = new HashMap<String, Object>();
                orgMap.put(EventBusConstant.TYPE, EventBusConstant.ACTIVITY_TO_ORGANIZATION);
                orgMap.put(EventBusConstant.OPERATE_ID, bean.user_id);
                EventBus.getDefault().post(orgMap);
            }
        });
        // 设置适配器

    }

    /**
     * 判断是否是添加成员
     *
     * @return
     */
    private boolean isAddMember() {
        if (ChatInfoActivity.MEMBER_ADD.equals(fromType)) {
            return true;
        }
        return false;
    }

    /**
     * 判断是否是删除成员
     *
     * @return
     */
    private boolean isMemberMin() {
        if (ChatInfoActivity.MEMBER_MIN.equals(fromType)) {
            return true;
        }
        return false;
    }

    /**
     * 判断是否由单聊变成群聊
     *
     * @return
     */
    private boolean isSingleChatToGroup() {
        if (isAddMember() && TextUtils.isEmpty(group_id)) {
            return true;
        }
        return false;
    }

    /**
     * 弹出删除确认对话框
     */
    private void showConfirmDialog() {
        DialogHelp.getConfirmDialog(mContext,
                String.format(getResources().getString(R.string.group_member_delete_confirm), getSelectUserName()),
                "",
                getResources().getString(R.string.think_again_and_again),
                getResources().getString(R.string.delete),
                null,
                new ButtonClickListener() {
                    @Override
                    public void buttonClick(View view) {
                        DeleteGroupMembers();
                    }
                })
                .setContentVisible(View.GONE).show();
    }

    /**
     * 获取所有选择的成员的字符串
     *
     * @return
     */
    private String getSelectUserName() {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < selectUserList.size() - 1; i++) {
            sb.append(selectUserList.get(i).user_name + "，");
        }
        sb.append(selectUserList.get(selectUserList.size() - 1).user_name);
        return sb.toString();
    }

    /**
     * 创建临时会话的方法
     */
    private void createGroupChat() {
        showWaitDialog();
        Map<String, Object> groupMap = new HashMap<>();
        ArrayList<OrgDeptUserBean> newChatList = new ArrayList<>();
        newChatList.addAll(currentUserList);
        newChatList.addAll(selectUserList);
        groupMap.put("user_id", user_id);
        groupMap.put("group_orgid", MyInfoUtil.getUserDeptId());
        groupMap.put("userList", newChatList);
        OkHttpManager.getInstance().commonRequest(Constants.CREATE_USER_GROUP, groupMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BaseReturnBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        T.showShort(mContext, e.getMessage());
                    }


                    @Override
                    public void onNext(BaseReturnBean baseReturnBean) {
                        hideWaitDialog();
                        if (ErrorCode.SUCCESS_CODE_WNX.equals(baseReturnBean.code)) {
                            Bundle dataBundle = new Bundle();
                            if (isAddMember()) {
                                T.showShort(mContext, R.string.group_member_add_success);
//                    LocalGroupOperateHelper.inviteIntoGroup(mContext, group_id, newAddList);
                            } else if (isMemberMin()) {
                                T.showShort(mContext, R.string.group_member_delete_success);
//                    LocalGroupOperateHelper.removeMemberFromGroup(mContext, group_id, deleteUserList);
                            } else {
//                    LocalGroupOperateHelper.inviteIntoGroup(mContext, group_id, selectUserList);
                                T.showShort(mContext, R.string.group_create_success);
                                Notifier.getInstance().isNeedNotice = false;
                            }
                            try {
                                JSONObject dataJson = new JSONObject(baseReturnBean.data);
                                String groupId = dataJson.optString("group_id");
                                String group_logo = dataJson.optString("group_logo");
                                LogUtil.d("创建成功" + groupId + ">>>" + group_logo);
                                dataBundle.putString(BldNavigation.SENDER_ID, groupId);
                                dataBundle.putInt(BldNavigation.CHAT_TYPE, MsgType.CHAT_CROUP.toNumber());
                                dataBundle.putString(BldNavigation.CHAT_NAME, "");
                                dataBundle.putString(BldNavigation.CHAT_SENDER_LOGO, "");
                                dataBundle.putInt(BldNavigation.GROUP_TYPE, Type.GroupType.TEMP_GROUP); //刚创建的为临时会话
                                Navigator.startChatActivity(mContext, dataBundle);
                                finish();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            T.showShort(mContext, baseReturnBean.desc);
                        }
                    }
                });

    }

    /**
     * 添加成员的方法
     */
    private void AddGroupMembers() {
        showWaitDialog();
        ArrayList<OrgDeptUserBean> newAddList = new ArrayList<>();

        for (OrgDeptUserBean bean : selectUserList) {
            if (!currentUserIdList.contains(bean.user_id)) {
                newAddList.add(bean);
            }
        }
        Map<String, Object> groupMap = new HashMap<>();
        groupMap.put("user_id", user_id);
        groupMap.put("group_id", group_id);
        groupMap.put("userList", newAddList);
        OkHttpManager.getInstance().commonRequest(Constants.ADD_GROUP_MEMBER, groupMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BaseReturnBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        T.showShort(mContext, e.getMessage());
                    }


                    @Override
                    public void onNext(BaseReturnBean baseReturnBean) {
                        hideWaitDialog();
                        if (ErrorCode.SUCCESS_CODE_WNX.equals(baseReturnBean.code)) {
                            Bundle dataBundle = new Bundle();
                            if (isAddMember()) {
                                T.showShort(mContext, R.string.group_member_add_success);
//                    LocalGroupOperateHelper.inviteIntoGroup(mContext, group_id, newAddList);
                            } else if (isMemberMin()) {
                                T.showShort(mContext, R.string.group_member_delete_success);
//                    LocalGroupOperateHelper.removeMemberFromGroup(mContext, group_id, deleteUserList);
                            } else {
//                    LocalGroupOperateHelper.inviteIntoGroup(mContext, group_id, selectUserList);
                                T.showShort(mContext, R.string.group_create_success);
                            }
                            try {
                                JSONObject dataJson = new JSONObject(baseReturnBean.data);
                                String groupId = dataJson.optString("group_id");
                                String group_logo = dataJson.optString("group_logo");
                                LogUtil.d("创建成功" + groupId + ">>>" + group_logo);
                                dataBundle.putString(BldNavigation.SENDER_ID, groupId);
                                dataBundle.putInt(BldNavigation.CHAT_TYPE, MsgType.CHAT_CROUP.toNumber());
                                dataBundle.putString(BldNavigation.CHAT_NAME, "");
                                dataBundle.putString(BldNavigation.CHAT_SENDER_LOGO, "");
                                dataBundle.putInt(BldNavigation.GROUP_TYPE, group_type);
                                Navigator.startChatActivity(mContext, dataBundle);
                                finish();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            T.showShort(mContext, baseReturnBean.desc);
                        }
                    }
                });

    }

    /**
     * 删除群组成员
     */
    private void DeleteGroupMembers() {
        showWaitDialog();
        Map<String, Object> groupMap = new HashMap<>();
        groupMap.put("user_id", user_id);
        groupMap.put("group_id", group_id);
        groupMap.put("userList", selectUserList);
        OkHttpManager.getInstance().commonRequest(Constants.EXIT_GROUP, groupMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BaseReturnBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        T.showShort(mContext, e.getMessage());
                    }


                    @Override
                    public void onNext(BaseReturnBean baseReturnBean) {
                        hideWaitDialog();
                        if (ErrorCode.SUCCESS_CODE_WNX.equals(baseReturnBean.code)) {
                            Bundle dataBundle = new Bundle();
                            if (isAddMember()) {
                                T.showShort(mContext, R.string.group_member_add_success);
//                    LocalGroupOperateHelper.inviteIntoGroup(mContext, group_id, newAddList);
                            } else if (isMemberMin()) {
                                T.showShort(mContext, R.string.group_member_delete_success);
//                    LocalGroupOperateHelper.removeMemberFromGroup(mContext, group_id, deleteUserList);
                            } else {
//                    LocalGroupOperateHelper.inviteIntoGroup(mContext, group_id, selectUserList);
                                T.showShort(mContext, R.string.group_create_success);
                            }
                            try {
                                JSONObject dataJson = new JSONObject(baseReturnBean.data);
                                String groupId = dataJson.optString("group_id");
                                String group_logo = dataJson.optString("group_logo");
                                LogUtil.d("创建成功" + groupId + ">>>" + group_logo);
                                dataBundle.putString(BldNavigation.SENDER_ID, groupId);
                                dataBundle.putInt(BldNavigation.CHAT_TYPE, MsgType.CHAT_CROUP.toNumber());
                                dataBundle.putString(BldNavigation.CHAT_NAME, "");
                                dataBundle.putString(BldNavigation.CHAT_SENDER_LOGO, "");
                                dataBundle.putInt(BldNavigation.GROUP_TYPE, group_type);
                                Navigator.startChatActivity(mContext, dataBundle);
                                finish();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            T.showShort(mContext, baseReturnBean.desc);
                        }
                    }
                });

    }


//    Subscriber<BaseReturnBean> groupResult = ;

    public void refreshHorizonAdapter() {
        mHorizonScroll.initDatas(horizonAdapter);
    }

    public void refreshMember() {
        memberSelect = selectUserList.size();
        if (isMemberMin()) {
            mTitleBar.setRightLayoutTextView(String.format(getResources().getString(R.string
                    .number_member_delete_select), memberSelect + ""));
        } else {
            mTitleBar.setRightLayoutTextView(String.format(getResources().getString(R.string.number_member_select),
                    memberSelect + ""));
        }
    }

    /**
     * fragment 切换
     *
     * @param from
     * @param to
     */
    public void switchContent(Fragment from, Fragment to, int position) {
        if (currentFragment != to) {
            currentFragment = to;
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            if (!to.isAdded()) { // 先判断是否被add过
                transaction.hide(from)
                        .add(R.id.container, to, tags[position]).commit(); // 隐藏当前的fragment，add下一个到Activity中
            } else {
                transaction.hide(from).show(to).commit(); // 隐藏当前的fragment，显示下一个
            }
        }
    }


    public boolean judgeIsHaveBeanById(OrgDeptUserBean bean) {
        for (OrgDeptUserBean mBean : selectUserList) {
            if (mBean.user_id.equals(bean.user_id)) {
                return true;
            }
        }
        return false;
    }


    /**
     * 对单个bean选择或者取消的操作
     *
     * @param operateBean
     * @param isSelectCancel
     */
    private void selectOrCancelSingleOperate(OrgDeptUserBean operateBean, boolean isSelectCancel) {
//        if (isMemberMin()) {
//            boolean isHasThisBean = false;
//            int index = -1;
//            for (OrgDeptUserBean mBean : deleteUserList) {
//                if (mBean.user_id.equals(operateBean.user_id)) {
//                    isHasThisBean = true;
//                    index = deleteUserList.indexOf(mBean);
//                    break;
//                }
//            }
//            if (!isHasThisBean && !isSelectCancel) {
//                deleteUserList.add(operateBean);
//            }
//            if (isHasThisBean && isSelectCancel) {
//                //不存在对应bean且选择操作
//                deleteUserList.remove(index);
//            }
//
//        }


        boolean isHasThisBean = false;
        int index = -1;
        for (OrgDeptUserBean mBean : selectUserList) {
            if (mBean.user_id.equals(operateBean.user_id)) {
                isHasThisBean = true;
                index = selectUserList.indexOf(mBean);
                break;
            }
        }

        if (isHasThisBean && !isSelectCancel) {
            //存在对应bean，切取消选择操作
            selectUserList.remove(index);
        }
        if (!isHasThisBean && isSelectCancel) {
            //不存在对应bean且选择操作
            selectUserList.add(operateBean);
        }
        refreshHorizonAdapter();
        refreshMember();
    }


    /**
     * 列表处理
     *
     * @param newList
     */
    private void membersDeal(List<OrgDeptUserBean> newList, boolean operate) {
        HashSet<String> userIdSet = new HashSet<>();
        if (operate) {
            for (OrgDeptUserBean bean : selectUserList) {
                userIdSet.add(bean.user_id);
            }
            for (OrgDeptUserBean newbean : newList) {
                if (!userIdSet.contains(newbean.user_id)) {
                    selectUserList.add(newbean);
                    userIdSet.add(newbean.user_id);
                }
            }
        } else {
            for (OrgDeptUserBean bean : newList) {
                userIdSet.add(bean.user_id);
            }
            List<OrgDeptUserBean> tempList = new ArrayList<>();
            tempList.addAll(selectUserList);
            for (OrgDeptUserBean newbean : tempList) {
                if (userIdSet.contains(newbean.user_id)) {
                    boolean isRemove = selectUserList.remove(newbean);
//                    userIdSet.remove(newbean.user_id);
                }
            }
        }
    }

    @Override
    public void onEventMainThread(Map inParam) {
        super.onEventMainThread(inParam);
        if (inParam.get(EventBusConstant.TYPE) == null) {
            return;
        }
        String type = inParam.get(EventBusConstant.TYPE).toString();
        LogUtil.d(TAG, "wubaojie>>>onEventMainThread: type:" + type);
        if (type.equals(EventBusConstant.ADDRESSBOOK_TO_ACTIVITY)) {
            boolean isSelectCancel = (Boolean) inParam.get(EventBusConstant.SELECT_OR_CANCEM);
            //通讯录I过来的 3个
            OrgDeptUserBean operateBean = (OrgDeptUserBean) inParam.get(EventBusConstant.SINGLE_MEMBER);
            selectOrCancelSingleOperate(operateBean, isSelectCancel);
        } else if (type.equals(EventBusConstant.ORGANIZATION_TO_ACTIVITY)) {
            boolean isSelectCancel = (Boolean) inParam.get(EventBusConstant.SELECT_OR_CANCEM);
            //组织机构过来的
            String numberSelect = (String) inParam.get(EventBusConstant.NUMBER_SELECT);
            if (EventBusConstant.SINGLE_MEMBER.equals(numberSelect)) {
                //选择单个
                OrgDeptUserBean operateBean = (OrgDeptUserBean) inParam.get(EventBusConstant.SINGLE_MEMBER);
                selectOrCancelSingleOperate(operateBean, isSelectCancel);
            } else if (EventBusConstant.LIST_MEMBER.equals(numberSelect)) {
                //选择多个
                List<OrgDeptUserBean> operateList = (List<OrgDeptUserBean>) inParam.get(EventBusConstant.LIST_MEMBER);
                LogUtil.d("selectUserList.size>>" + selectUserList.size());
                LogUtil.d("operateList.size>>" + operateList.size());
                membersDeal(operateList, isSelectCancel);
//                if (!isSelectCancel) {
//                    int index = 0;
//                    for (OrgDeptUserBean oldBean : tempList) {
//                        for (OrgDeptUserBean newNean : operateList) {
//                            if (oldBean != null && oldBean.user_id.equals(newNean.user_id)) {
//                                selectUserList.remove(oldBean);
//                                LogUtil.d("tempList.size>>" + tempList.size());
//                                //找到符合的对象,改变状态
//                                break;
//                            }
//                        }
//                        index++;
//                    }
//                    for (OrgDeptUserBean newNean : operateList) {
//                        if (currentUserIdList.contains(newNean.user_id)) {
//                            selectUserList.remove(currentUserIdList.indexOf());
//                            LogUtil.d("tempList.size>>" + tempList.size());
//                        }
//                    }
//                    LogUtil.d("selectUserList.size>>" + selectUserList.size());
//
//                } else {
//                    if (selectUserList.size() == 0) {
//                        selectUserList.addAll(operateList);
//                    } else {
//                        for (OrgDeptUserBean newNean : operateList) {
//                            for (OrgDeptUserBean oldBean : tempList) {
//                                if (oldBean != null && !oldBean.user_id.equals(newNean.user_id)) {
//                                    selectUserList.add(newNean);
//                                    //找到符合的对象,改变状态
//                                    break;
//                                }
//                            }
//                        }
//                    }
//                }
//                tempList.clear();
                refreshHorizonAdapter();
                refreshMember();
            }
        }


//        if (inParam.get(EventBusConstant.TYPE).equals(EventBusConstant.ACTION_SELECT_MEMBER_ACTIVITY)) {
//            //选择单个
//            if (EventBusConstant.SINGLE_MEMBER.equals(inParam.get(EventBusConstant.ACTION_KEY))) {
//                OrgDeptUserBean bean = (OrgDeptUserBean) inParam.get(EventBusConstant.ACTION_VALUE);
//                if ((Boolean) inParam.get(EventBusConstant.SELECT_OR_CANCEM)) {
//                    //选中
//                    if (!selectUserList.contains(bean)) {
//                        selectUserList.add(bean);
//                        refreshHorizonAdapter();
//                        refreshMember();
//                    }
//
//                } else {
//                    //取消操作
//                    if (selectUserList.contains(bean)) {
//                        selectUserList.remove(bean);
//                        refreshHorizonAdapter();
//                        refreshMember();
//                    }
//                }
//
//            } else if (EventBusConstant.LIST_MEMBER.equals(inParam.get(EventBusConstant.ACTION_KEY))) {
//                //选择多个
//                List<OrgDeptUserBean> addList = (List<OrgDeptUserBean>) inParam.get(EventBusConstant.ACTION_VALUE);
//
//                if ((Boolean) inParam.get(EventBusConstant.SELECT_OR_CANCEM)) {
//                    for (OrgDeptUserBean bean : addList) {
//                        if (!selectUserList.contains(bean)) {
//                            //不包含的情况下，添加
//                            selectUserList.add(bean);
//                        }
//                    }
//                    refreshHorizonAdapter();
//                    refreshMember();
//                    //选中
//                } else {
//                    //取消操作
//                    for (OrgDeptUserBean bean : addList) {
//                        if (selectUserList.contains(bean)) {
//                            //不包含的情况下，添加
//                            selectUserList.remove(bean);
//                        }
//                    }
//                    refreshHorizonAdapter();
//                    refreshMember();
//                }
//            }
//        }


    }

}
